<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绩效权重设置</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Arial';
            background-color: #f5f5f5;
        }

        .container {
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            text-align: center;
        }

        .header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }

        .header p {
            margin: 0;
            opacity: 0.9;
            font-size: 16px;
        }

        .toolbar {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .main-content {
            flex: 1;
            padding: 10px;
            overflow: auto;
        }

        .weight-table {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .weight-table .el-table__body td {
            padding: 4px 0;
        }

        .weight-table .el-table__header th {
            padding: 8px 0;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #909399;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            display: block;
        }

        .weight-value {
            font-weight: bold;
            color: #409eff;
        }

        .weight-value.high {
            color: #67c23a;
        }

        .weight-value.low {
            color: #e6a23c;
        }

        .operation-buttons {
            display: flex;
            gap: 5px;
        }

        .employee-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .employee-name {
            font-weight: 500;
            color: #2c3e50;
        }

        .employee-id {
            font-size: 12px;
            color: #909399;
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
        }

        .form-col {
            flex: 1;
        }

        .weight-input-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .weight-percentage {
            color: #606266;
            font-size: 12px;
        }

        /* 特殊设置紧凑样式 */
        .special-settings-content .el-form-item {
            margin-bottom: 15px;
        }

        .special-settings-content .el-card__body {
            padding: 15px;
        }

        .special-settings-content .el-card__header {
            padding: 12px 15px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <!-- <div class="header">
                <h1>绩效权重设置</h1>
                <p>为员工设置个人绩效权重和生产绩效权重</p>
            </div> -->

            <!-- <div class="toolbar">
                <div>
                    <h3>绩效权重设置</h3>
                </div>
            </div> -->

            <!-- Tab 导航 -->
            <div class="main-content">
                <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="border-card" style="margin: 0;">
                    <el-tab-pane label="默认设置" name="special">
                        <!-- 特殊设置内容 -->
                        <div class="special-settings-content">
                            <!-- 特殊设置按钮 -->
                            <div style="padding: 15px 20px 0 20px;">
                                <el-button type="primary" @click="saveSpecialSettings" size="small"
                                    icon="el-icon-check">
                                    保存设置
                                </el-button>
                            </div>
                            <el-form :model="specialSettings" label-width="120px" style="padding: 15px 20px;">
                                <el-card shadow="never" style="margin-bottom: 15px;">
                                    <div slot="header">
                                        <span>默认计算公式</span>
                                    </div>
                                    <div
                                        style="background-color: #f8f9fa; padding: 12px; border-radius: 4px; margin-bottom: 12px;">
                                        <div style="font-size: 15px; font-weight: 500; margin-bottom: 8px;">生产奖金最终发放额 =
                                            生产绩效 × {{ specialSettings.defaultProductionWeight }}% + 个人绩效 × {{
                                            specialSettings.defaultPersonalWeight }}%</div>
                                        <div style="color: #606266; font-size: 12px;">适用于所有未在特殊设置中指定的员工</div>
                                    </div>

                                    <div class="form-row">
                                        <div class="form-col">
                                            <el-form-item label="生产绩效权重">
                                                <div class="weight-input-group">
                                                    <el-input-number v-model="specialSettings.defaultProductionWeight"
                                                        :min="0" :max="100" :precision="1" style="width: 150px;"
                                                        @change="onDefaultWeightChange">
                                                    </el-input-number>
                                                    <span class="weight-percentage">%</span>
                                                </div>
                                            </el-form-item>
                                        </div>
                                        <div class="form-col">
                                            <el-form-item label="个人绩效权重">
                                                <div class="weight-input-group">
                                                    <el-input-number v-model="specialSettings.defaultPersonalWeight"
                                                        :min="0" :max="100" :precision="1" style="width: 150px;"
                                                        @change="onDefaultWeightChange">
                                                    </el-input-number>
                                                    <span class="weight-percentage">%</span>
                                                </div>
                                            </el-form-item>
                                        </div>
                                    </div>

                                    <el-form-item>
                                        <el-alert v-if="defaultWeightTotal !== 100"
                                            :title="`权重总计: ${defaultWeightTotal}% (权重总和应为100%)`" type="warning"
                                            show-icon :closable="false">
                                        </el-alert>
                                        <el-alert v-else title="权重总计: 100% ✓ 配置正确" type="success" show-icon
                                            :closable="false">
                                        </el-alert>
                                    </el-form-item>
                                </el-card>

                                <el-card shadow="never">
                                    <div slot="header">
                                        <span>Supervisor 特殊计算公式</span>
                                    </div>
                                    <div
                                        style="background-color: #f0f9ff; padding: 12px; border-radius: 4px; margin-bottom: 12px;">
                                        <div style="font-size: 15px; font-weight: 500; margin-bottom: 8px;">生产奖金最终发放额 =
                                            生产绩效 × {{ specialSettings.supervisorProductionWeight }}% + 个人绩效 × {{
                                            specialSettings.supervisorPersonalWeight }}%</div>
                                        <div style="color: #606266; font-size: 12px;">适用于职位中包含 "supervisor" 的员工</div>
                                    </div>

                                    <div class="form-row">
                                        <div class="form-col">
                                            <el-form-item label="生产绩效权重">
                                                <div class="weight-input-group">
                                                    <el-input-number
                                                        v-model="specialSettings.supervisorProductionWeight" :min="0"
                                                        :max="100" :precision="1" style="width: 150px;"
                                                        @change="onSupervisorWeightChange">
                                                    </el-input-number>
                                                    <span class="weight-percentage">%</span>
                                                </div>
                                            </el-form-item>
                                        </div>
                                        <div class="form-col">
                                            <el-form-item label="个人绩效权重">
                                                <div class="weight-input-group">
                                                    <el-input-number v-model="specialSettings.supervisorPersonalWeight"
                                                        :min="0" :max="100" :precision="1" style="width: 150px;"
                                                        @change="onSupervisorWeightChange">
                                                    </el-input-number>
                                                    <span class="weight-percentage">%</span>
                                                </div>
                                            </el-form-item>
                                        </div>
                                    </div>

                                    <el-form-item>
                                        <el-alert v-if="supervisorWeightTotal !== 100"
                                            :title="`权重总计: ${supervisorWeightTotal}% (权重总和应为100%)`" type="warning"
                                            show-icon :closable="false">
                                        </el-alert>
                                        <el-alert v-else title="权重总计: 100% ✓ 配置正确" type="success" show-icon
                                            :closable="false">
                                        </el-alert>
                                    </el-form-item>
                                </el-card>


                            </el-form>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="员工设置" name="employee">
                        <!-- 员工设置内容 -->
                        <div class="employee-settings-content">
                            <!-- 员工设置按钮 -->
                            <div style="padding: 20px 20px 0 20px;">
                                <el-button type="primary" size="small" @click="showAddDialog" icon="el-icon-plus">
                                    新增设置
                                </el-button>
                                <el-button size="small" @click="refreshData" icon="el-icon-refresh"
                                    style="margin-left: 10px;">
                                    刷新
                                </el-button>
                            </div>

                            <el-empty v-if="weightList.length === 0" description="暂无权重设置">
                            </el-empty>

                            <div v-else class="weight-table" style="margin: 20px 20px 20px 20px;">
                                <el-table :data="weightList" border style="width: 100%;" stripe>
                                    <el-table-column prop="division" label="Division" min-width="200">
                                        <template slot-scope="scope">
                                            <div style="font-weight: 500; color: #2c3e50;">{{ scope.row.division }}
                                            </div>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="bu" label="BU" min-width="300">
                                        <template slot-scope="scope">
                                            <div style="font-weight: 500;">{{ scope.row.bu }}</div>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeeId" label="工号" width="120" align="center">
                                        <template slot-scope="scope">
                                            <div class="employee-info">
                                                <span class="employee-id">{{ scope.row.employeeId }}</span>
                                            </div>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="employeeName" label="姓名" width="120" align="center">
                                        <template slot-scope="scope">
                                            <div class="employee-name">{{ scope.row.employeeName }}</div>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="productionWeight" label="生产绩效权重" width="140" align="center">
                                        <template slot-scope="scope">
                                            <div :class="getWeightClass(scope.row.productionWeight)"
                                                class="weight-value">
                                                {{ scope.row.productionWeight }}%
                                            </div>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="personalWeight" label="个人绩效权重" width="140" align="center">
                                        <template slot-scope="scope">
                                            <div :class="getWeightClass(scope.row.personalWeight)" class="weight-value">
                                                {{ scope.row.personalWeight }}%
                                            </div>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="creator" label="创建人" width="120" align="center">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.creator }}</span>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="createTime" label="创建时间" width="160" align="center">
                                        <template slot-scope="scope">
                                            <span>{{ formatDateTime(scope.row.createTime) }}</span>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="modifier" label="修改人" width="120" align="center">
                                        <template slot-scope="scope">
                                            <span v-if="scope.row.modifier">{{ scope.row.modifier }}</span>
                                            <span v-else style="color: #909399;">-</span>
                                        </template>
                                    </el-table-column>

                                    <el-table-column prop="modifyTime" label="修改时间" width="160" align="center">
                                        <template slot-scope="scope">
                                            <span v-if="scope.row.modifyTime">{{ formatDateTime(scope.row.modifyTime)
                                                }}</span>
                                            <span v-else style="color: #909399;">-</span>
                                        </template>
                                    </el-table-column>

                                    <el-table-column label="操作" width="140" align="center" fixed="right">
                                        <template slot-scope="scope">
                                            <div class="operation-buttons">
                                                <el-button type="text" size="small"
                                                    @click="editWeightSetting(scope.row)" style="color: #409eff;">
                                                    编辑
                                                </el-button>
                                                <el-button type="text" size="small"
                                                    @click="deleteWeightSetting(scope.row)" style="color: #f56c6c;">
                                                    删除
                                                </el-button>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>

        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogMode === 'add' ? '新增权重设置' : '编辑权重设置'" :visible.sync="dialogVisible" width="700px">
            <el-form :model="formData" :rules="formRules" ref="weightForm" label-width="120px">

                <!-- 用户选择区域 -->
                <el-form-item label="选择用户" prop="selectedUser" v-if="dialogMode === 'add'">
                    <el-select v-model="formData.selectedUser" placeholder="请选择用户" style="width: 100%;" filterable
                        @change="onUserSelected">
                        <el-option-group v-for="division in groupedUsers" :key="division.division"
                            :label="division.division">
                            <el-option v-for="user in division.users" :key="user.id"
                                :label="`${user.name} (${user.employeeId}) - ${user.bu}`" :value="user.id">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <div style="font-weight: 500;">{{ user.name }} ({{ user.employeeId }})</div>
                                        <div style="font-size: 12px; color: #909399;">{{ user.division }} - {{ user.bu
                                            }}</div>
                                    </div>
                                </div>
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>

                <!-- 编辑模式下显示用户信息 -->
                <div v-if="dialogMode === 'edit'"
                    style="background-color: #f8f9fa; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
                    <h4 style="margin: 0 0 10px 0; color: #2c3e50;">用户信息</h4>
                    <div class="form-row">
                        <div class="form-col">
                            <div><strong>Division:</strong> {{ formData.division }}</div>
                            <div><strong>BU:</strong> {{ formData.bu }}</div>
                        </div>
                        <div class="form-col">
                            <div><strong>工号:</strong> {{ formData.employeeId }}</div>
                            <div><strong>姓名:</strong> {{ formData.employeeName }}</div>
                        </div>
                    </div>
                </div>

                <!-- 权重设置区域 -->
                <div class="form-row">
                    <div class="form-col">
                        <el-form-item label="生产绩效权重" prop="productionWeight">
                            <div class="weight-input-group">
                                <el-input-number v-model="formData.productionWeight" :min="0" :max="100" :precision="1"
                                    style="width: 150px;" @change="onWeightChange">
                                </el-input-number>
                                <span class="weight-percentage">%</span>
                            </div>
                        </el-form-item>
                    </div>
                    <div class="form-col">
                        <el-form-item label="个人绩效权重" prop="personalWeight">
                            <div class="weight-input-group">
                                <el-input-number v-model="formData.personalWeight" :min="0" :max="100" :precision="1"
                                    style="width: 150px;" @change="onWeightChange">
                                </el-input-number>
                                <span class="weight-percentage">%</span>
                            </div>
                        </el-form-item>
                    </div>
                </div>

                <el-form-item>
                    <el-alert v-if="weightTotal !== 100" :title="`权重总计: ${weightTotal}% (权重总和应为100%)`" type="warning"
                        show-icon :closable="false">
                    </el-alert>
                    <el-alert v-else title="权重总计: 100% ✓ 配置正确" type="success" show-icon :closable="false">
                    </el-alert>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="saveWeightSetting"
                    :disabled="weightTotal !== 100 || (dialogMode === 'add' && !formData.selectedUser)" size="small">
                    {{ dialogMode === 'add' ? '新增' : '保存' }}
                </el-button>
            </div>
        </el-dialog>
    </div>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="user-data.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    weightList: [],
                    dialogVisible: false,
                    dialogMode: 'add', // 'add' or 'edit'
                    currentUser: '系统管理员', // 模拟当前用户
                    editingId: null,
                    activeTab: 'special', // 默认显示特殊设置
                    formData: {
                        selectedUser: '',
                        division: '',
                        bu: '',
                        employeeId: '',
                        employeeName: '',
                        productionWeight: 50,
                        personalWeight: 50
                    },
                    formRules: {
                        selectedUser: [
                            { required: true, message: '请选择用户', trigger: 'change' }
                        ],
                        productionWeight: [
                            { required: true, message: '请设置生产绩效权重', trigger: 'blur' }
                        ],
                        personalWeight: [
                            { required: true, message: '请设置个人绩效权重', trigger: 'blur' }
                        ]
                    },
                    // 用户列表数据 - 从user-data.js加载
                    availableUsers: [],

                    // 特殊设置
                    specialSettings: {
                        defaultProductionWeight: 30,
                        defaultPersonalWeight: 70,
                        supervisorProductionWeight: 50,
                        supervisorPersonalWeight: 50
                    }
                }
            },
            computed: {
                weightTotal() {
                    return (this.formData.productionWeight || 0) + (this.formData.personalWeight || 0);
                },

                // 将用户按Division分组
                groupedUsers() {
                    const groups = {};
                    this.availableUsers.forEach(user => {
                        if (!groups[user.division]) {
                            groups[user.division] = {
                                division: user.division,
                                users: []
                            };
                        }
                        groups[user.division].users.push(user);
                    });

                    // 对每个分组内的用户按BU和姓名排序
                    Object.values(groups).forEach(group => {
                        group.users.sort((a, b) => {
                            if (a.bu !== b.bu) {
                                return a.bu.localeCompare(b.bu);
                            }
                            return a.name.localeCompare(b.name);
                        });
                    });

                    return Object.values(groups).sort((a, b) =>
                        a.division.localeCompare(b.division)
                    );
                },

                // 默认权重总计
                defaultWeightTotal() {
                    return (this.specialSettings.defaultProductionWeight || 0) + (this.specialSettings.defaultPersonalWeight || 0);
                },

                // Supervisor权重总计
                supervisorWeightTotal() {
                    return (this.specialSettings.supervisorProductionWeight || 0) + (this.specialSettings.supervisorPersonalWeight || 0);
                }
            },
            mounted() {
                this.loadWeightData();
                this.loadUserDataFromJS();
                this.loadSpecialSettings();
            },
            methods: {
                // 加载权重数据
                loadWeightData() {
                    const stored = localStorage.getItem('performanceWeightData');
                    if (stored) {
                        this.weightList = JSON.parse(stored);
                    }
                },

                // 保存权重数据
                saveWeightData() {
                    localStorage.setItem('performanceWeightData', JSON.stringify(this.weightList));
                },

                // 加载用户数据从user-data.js
                loadUserDataFromJS() {
                    // 使用user-data.js中的userList数据
                    if (typeof userList !== 'undefined' && userList.length > 0) {
                        // 转换数据格式以匹配权重设置需求
                        this.availableUsers = userList.map(user => ({
                            id: user.id,
                            name: user.name,
                            employeeId: user.code, // 使用code作为employeeId
                            division: user.division,
                            bu: user.bu,
                            location: user.locatiom, // 注意原数据中拼写是locatiom
                            hrType: user.hrType
                        }));
                        console.log(`已加载${this.availableUsers.length}个用户数据`);
                    } else {
                        console.warn('user-data.js中没有找到userList数据');
                        this.$message.warning('无法加载用户数据，请检查user-data.js文件');
                    }
                },

                // 显示新增对话框
                showAddDialog() {
                    this.dialogMode = 'add';
                    this.editingId = null;
                    this.formData = {
                        selectedUser: '',
                        division: '',
                        bu: '',
                        employeeId: '',
                        employeeName: '',
                        productionWeight: 50,
                        personalWeight: 50
                    };
                    this.dialogVisible = true;
                },

                // 用户选择变化处理
                onUserSelected(userId) {
                    const selectedUser = this.availableUsers.find(user => user.id === userId);
                    if (selectedUser) {
                        this.formData.division = selectedUser.division;
                        this.formData.bu = selectedUser.bu;
                        this.formData.employeeId = selectedUser.employeeId;
                        this.formData.employeeName = selectedUser.name;
                    }
                },

                // 编辑权重设置
                editWeightSetting(row) {
                    this.dialogMode = 'edit';
                    this.editingId = row.id;
                    this.formData = { ...row };
                    this.dialogVisible = true;
                },

                // 保存权重设置
                saveWeightSetting() {
                    this.$refs.weightForm.validate((valid) => {
                        if (valid && this.weightTotal === 100) {
                            const now = new Date().toISOString();

                            if (this.dialogMode === 'add') {
                                // 检查是否已存在相同员工的设置
                                const existing = this.weightList.find(item =>
                                    item.employeeId === this.formData.employeeId
                                );
                                if (existing) {
                                    this.$message.warning('该员工已存在权重设置');
                                    return;
                                }

                                const newSetting = {
                                    id: 'weight_' + Date.now(),
                                    division: this.formData.division,
                                    bu: this.formData.bu,
                                    employeeId: this.formData.employeeId,
                                    employeeName: this.formData.employeeName,
                                    productionWeight: this.formData.productionWeight,
                                    personalWeight: this.formData.personalWeight,
                                    creator: this.currentUser,
                                    createTime: now,
                                    modifier: null,
                                    modifyTime: null
                                };
                                this.weightList.push(newSetting);
                                this.$message.success('权重设置新增成功');
                            } else {
                                const index = this.weightList.findIndex(item => item.id === this.editingId);
                                if (index > -1) {
                                    this.weightList[index] = {
                                        ...this.weightList[index],
                                        productionWeight: this.formData.productionWeight,
                                        personalWeight: this.formData.personalWeight,
                                        modifier: this.currentUser,
                                        modifyTime: now
                                    };
                                    this.$message.success('权重设置修改成功');
                                }
                            }

                            this.saveWeightData();
                            this.dialogVisible = false;
                        }
                    });
                },

                // 删除权重设置
                deleteWeightSetting(row) {
                    this.$confirm(`确定要删除员工 ${row.employeeName}(${row.employeeId}) 的权重设置吗？`, '确认删除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const index = this.weightList.findIndex(item => item.id === row.id);
                        if (index > -1) {
                            this.weightList.splice(index, 1);
                            this.saveWeightData();
                            this.$message.success('删除成功');
                        }
                    }).catch(() => {
                        this.$message.info('已取消删除');
                    });
                },

                // 权重变化处理
                onWeightChange() {
                    // 可以在这里添加实时权重验证逻辑
                },

                // 获取权重样式类
                getWeightClass(weight) {
                    if (weight >= 70) return 'high';
                    if (weight >= 30) return '';
                    return 'low';
                },

                // 格式化日期时间
                formatDateTime(dateTimeString) {
                    if (!dateTimeString) return '-';
                    const date = new Date(dateTimeString);
                    return date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                },

                // 刷新数据
                refreshData() {
                    this.loadWeightData();
                    this.$message.success('数据已刷新');
                },

                // 特殊设置相关方法
                showSpecialSettingsDialog() {
                    this.specialSettingsVisible = true;
                },

                loadSpecialSettings() {
                    const stored = localStorage.getItem('bonusCalculationSettings');
                    if (stored) {
                        try {
                            const settings = JSON.parse(stored);
                            this.specialSettings = { ...this.specialSettings, ...settings };
                        } catch (e) {
                            console.warn('加载特殊设置失败，使用默认设置');
                        }
                    }
                },

                saveSpecialSettings() {
                    if (this.defaultWeightTotal === 100 && this.supervisorWeightTotal === 100) {
                        localStorage.setItem('bonusCalculationSettings', JSON.stringify(this.specialSettings));
                        this.$message.success('特殊设置保存成功');
                        this.specialSettingsVisible = false;
                    } else {
                        this.$message.error('请确保所有权重总和为100%');
                    }
                },

                // Tab 切换处理
                handleTabClick(tab) {
                    this.activeTab = tab.name;
                },

                onDefaultWeightChange() {
                    // 实时更新默认权重总计
                },

                onSupervisorWeightChange() {
                    // 实时更新Supervisor权重总计
                }
            }
        });
    </script>
</body>

</html>